﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Micrhard.FMCG.Server.Interface;
using Microhard.Core.DBUtility;
using Micrhard.FMCG.Server.DataAccess;
using Micrhard.FMCG.Server.DTO;
using Microhard.Core;
using Micrhard.FMCG.Server.Models;

namespace Micrhard.FMCG.Server.Impl
{
    public class SaleStatementImpl : IOrderStatement
    {
        private bool CreateReport(Guid companyid, string sys, DateTime latestdate, DateTime previousdate)
        {
            bool result = false;
            var dbnow = DateTime.Now.Date;
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            if (latestdate == dbnow)
            {
                //删除原有的报表
                var todel = db.ProductSaledOfDays.Where(p => p.DayOfSaled == dbnow && p.CompanyID == companyid
                    && p.HQCompanyCode == sys).ToList();
                todel.ForEach(t =>
                {
                    db.ProductSaledOfDays.DeleteObject(t);
                });
            }

            //遍历产品获取日销量
            var lts = db.SaleStatements.Where(t => t.CompanyID == companyid &&
                        t.DayOfStmp == latestdate && t.HQCompanyCode == sys).ToList();
            lts.ForEach(lt =>
            {
                bool toadd = false;
                bool toupdate = false;
                var sd = db.SaleStatements.SingleOrDefault(t => t.CompanyID == companyid &&
                   t.DayOfStmp == previousdate && t.HQCompanyCode == sys
                   && t.ProductCode == lt.ProductCode && t.StoreCode == lt.StoreCode);
                if (sd == null)
                {
                    toadd = true;
                }
                else if (lt.SaleVolumn > sd.SaleVolumn)
                {
                    toadd = true;
                    toupdate = true;
                }
                if (toadd)
                {
                    ProductSaledOfDay psd = new ProductSaledOfDay();
                    psd.CompanyID = companyid;
                    psd.DayOfSaled = dbnow;
                    psd.HQCompanyCode = sys;
                    psd.ProductCode = lt.ProductCode;
                    psd.ProductName = lt.ProductName;
                    if (toupdate)
                    {
                        psd.SaleTotalCount = lt.SalueVolumnCount - sd.SalueVolumnCount;
                        psd.SaleVolumn = lt.SaleVolumn - sd.SaleVolumn;
                        psd.AddReason = "Update";
                    }
                    else
                    {
                        psd.SaleTotalCount = lt.SalueVolumnCount;
                        psd.SaleVolumn = lt.SaleVolumn;
                        psd.AddReason = "New";
                    }
                    psd.SalingPrdID = lt.SalingPrdID;
                    psd.StoreCode = lt.StoreCode;
                    psd.StoreName = lt.StoreName;
                    psd.SubKAID = lt.SubKAID;
                    psd.SupplierCode = lt.SupplierCode;
                    psd.SupplierName = lt.SupplierName;
                    psd.ProductSaleVolumnOfDayID = Guid.NewGuid();
                    db.ProductSaledOfDays.AddObject(psd);
                    Console.WriteLine("公司:" + companyid + " System:" + sys + " 产品:" + psd.ProductName + " 金额:" + psd.SaleVolumn);
                }
            });
            try
            {

                db.SaveChanges();
                result = true;
            }
            catch (Exception ex)
            {
                Log.Error("IOrderStatement.CreateReport", ex);
            }
            Console.WriteLine("生成完毕");
            return result;
        }

        public void DoReport()
        {
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            //查询任务表是否有更新的任务
            var tasks = db.CreateProductDaySaledReportTasks.Where(p => p.Status == false).ToList();
            tasks.ForEach(t =>
            {
                t.Status = this.CreateReport(t.CompanyID.Value, t.System, t.LatestUpdateDataDate.Value, t.PeriousUpdateDataDate.Value);
            });
            if (tasks.Count > 0)
            {
                try
                {

                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    Log.Error("IOrderStatement.DoReport", ex);
                }
            }
        }

        public ExecutedResult AddInBatch(List<StatementModelInServer> model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrhardFMCGServerEntities db = new MicrhardFMCGServerEntities();
            //物美VRM是第二天早上，才会更新前一天的数据。
            var now = DateTime.Now.AddDays(-1);
            var companyid = model.First().CompanyID;
            var sys = model.First().HQCompanyCode;
            //获得最近一次数据
            var query = db.SaleStatements.Where(c => c.CompanyID == companyid && c.HQCompanyCode == sys)
    .OrderByDescending(p => p.DayOfStmp);
            var cnt = query.Count();
            DateTime timeList;
            decimal dbamount = 0;
            bool doupdate = false;
            bool doCreateReportTask = false;

            if (cnt > 0)
            {
                timeList = query.Select(x => x.DayOfStmp).First().Value;
                //累计合计是否发生变化
                var data = db.SaleStatements.Where(s => s.DayOfStmp == timeList
                    && s.CompanyID == companyid && s.HQCompanyCode == sys);
                if (data.Count() > 0)
                {
                    dbamount = data.Sum(p => p.SaleVolumn.Value);
                    //表示累计销售总额有变化
                    var currentAmount = model.Sum(s => s.SaleVolumn);
                    if (currentAmount > dbamount)
                    {
                        doupdate = true;
                        doCreateReportTask = true;
                    }
                }
            }
            else
            {
                doupdate = true;
                timeList = now;
            }

            if (doupdate)
            {
                model.ForEach(m =>
                {
                    //添加
                    var entity = m.ToEntity();
                    entity.DayOfStmp = now;
                    entity.StatementID = Guid.NewGuid();
                    //关联产品
                    var prdMapping = db.ProductSaleMappings.SingleOrDefault(p => p.KA.CustomerCode == m.HQCompanyCode &&
                        m.ProductCode == p.CustomerCode && p.KA.CompanyID == companyid);
                    if (prdMapping != null)
                    {
                        entity.SalingPrdID = prdMapping.PrdDepID;
                    }
                    //关联卖场
                    var subka = db.SubKAs.SingleOrDefault(s => s.CustomerCode == m.StoreCode
                        && s.KA.CustomerCode == m.HQCompanyCode && s.KA.CompanyID == companyid);
                    if (subka != null)
                    {
                        entity.SubKAID = subka.SubID;
                    }
                    db.SaleStatements.AddObject(entity);
                });

                if (doCreateReportTask)
                {
                    //有数据更新，记录到任务中
                    db.CreateProductDaySaledReportTasks.AddObject(new CreateProductDaySaledReportTask
                    {
                        CompanyID = companyid,
                        LatestUpdateDataDate = now,
                        PeriousUpdateDataDate = timeList,
                        Status = false,
                        System = sys
                    });
                }
            }

            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, ex.Message);
                Log.Error("IOrderStatement.Add", ex);
            }
            return rtn;
        }

        public ExecutedResult Add(StatementModelInServer model)
        {
            throw new NotImplementedException();
        }

        public ExecutedResult Update(StatementModelInServer model)
        {
            throw new NotImplementedException();
        }

        public ExecutedResult Delete(List<Guid> ids)
        {
            throw new NotImplementedException();
        }

        public ExecutedResult Delete(StatementModelInServer model)
        {
            throw new NotImplementedException();
        }

        public StatementModelInServer GetModelByID(Guid id)
        {
            throw new NotImplementedException();
        }

        public StatementModelInServer GetModelByModel(StatementModelInServer model)
        {
            throw new NotImplementedException();
        }

        public List<StatementModelInServer> Query(StatementModelInServer Model, int pageIndex, int pageSize, out int totalCount)
        {
            throw new NotImplementedException();
        }

        public List<StatementModelInServer> Query(StatementModelInServer Model)
        {
            return null;
        }

        public ScopeResult scope
        {
            set;
            get;
        }
    }
}
